package com.example.demo.service.impl;

import com.example.demo.entity.SessionEntity;
import com.example.demo.entity.UserEntity;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.SessionMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

import static com.example.demo.common.Constant.*;

/**
 * @DESCRIPTION:
 * @AUTOOR: Lee
 * @DATE: 2022年09月18日 1:08
 */
@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final SessionMapper sessionMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, SessionMapper sessionMapper) {
        this.userMapper = userMapper;
        this.sessionMapper = sessionMapper;
    }


    @Override
    public UserEntity createUser(UserEntity user) {
        userMapper.insert(user);
        return user;
    }


    @Override
    public void login(HttpServletRequest request, HttpServletResponse response, String userName, String passWord) {
        UserEntity userEntity = userMapper.selectOne(userName, passWord);
        if (userEntity == null) {
            throw new ServiceException("此用户不存在");
        }
        // create session id
        String randomVal = UUID.randomUUID().toString();
        createSession(userEntity.getId(), randomVal);
        Cookie cookie = new Cookie(SESSION_ID, randomVal);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public void createSession(Integer userId, String sessionId) {
        SessionEntity sessionEntity = sessionMapper.queryByUserId(userId);
        if (sessionEntity == null) {
            sessionEntity = new SessionEntity();
            sessionEntity.setUserId(userId);
            sessionEntity.setSessionId(sessionId);
            sessionMapper.insert(sessionEntity);
        } else {
            sessionEntity.setSessionId(sessionId);
            sessionMapper.updateById(sessionEntity);
        }
    }
}
